using System;
using System.Drawing.Imaging;
using System.Web;
using System.Drawing;
using System.IO;
using SinBiota.Model.Business.MapServices.Interfaces;

namespace Sinbiota.Web.Services
{
    public class TileLayerServer : IHttpHandler
    {
        // required interfaces:
        private readonly ITileLayerServices _tileLayerServices;

        public TileLayerServer()
        {
            _tileLayerServices = StructureMap.ObjectFactory.GetInstance<ITileLayerServices>();
        }

        public void ProcessRequest(HttpContext context)
        {
            Image image;
            //process GET parameters:
            var layer = context.Request.Params["layer"];
            // Test which type of image is being asked, thumbnail or tile; if 'thumb' is defined, thumbnail it is;
            if (!string.IsNullOrEmpty(context.Request.Params["thumb"]))
            {
                image = _tileLayerServices.GenerateThumbnail(layer, context.Request.Params["size"]);
            }
            else if (!string.IsNullOrEmpty(context.Request.Params["legend"]))
            {
                image = _tileLayerServices.GenerateLegend(layer);
            }
            else
            {
                // No thumb defined, generate tile image:
                image = _tileLayerServices.GenerateTileLayerImage(layer, context.Request.Params["quadkey"]);
            }
            // Write image in stream and dispose image
            InitImageResponse(context.Response);
            
           if (image == null) image = new Bitmap(1, 1);
            WritePngImageToStream(image, context.Response.OutputStream);   
            image.Dispose();
            
        }

        private static void InitImageResponse(HttpResponse response)
        {
            response.BufferOutput = true;
            response.Clear();
            response.ClearHeaders();
            response.ContentType = "image/png";
            response.Expires = 60;
            response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            response.Cache.SetNoServerCaching();
            response.Cache.SetNoStore();
            response.Cache.SetMaxAge(TimeSpan.FromHours(1));
        }

        private static void WritePngImageToStream(Image image, Stream stream)
        {
            if (image == null) return;
            var writeStream = new MemoryStream();
            image.Save(writeStream, ImageFormat.Png);
            writeStream.WriteTo(stream);
            writeStream.Dispose();
        }

        public bool IsReusable
        {
            get { return false; }
        }

    }
}
